// pages/service/service.js
import api from '@/utils/request'
import {points1,points2,points3,points4,points5,points6} from '@/utils/xt'
// 引入SDK核心类
var QQMapWX = require('../../components/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
        //polygons 多边形
        polygon:[{  
          points: points1,
           fillColor: "#4F94CD33",
            fillColor: "#ffff0033",
            strokeColor: "#FFF",
            strokeWidth: 2,
            zIndex: 5,
      },{  
        points: points2,
         fillColor: "#4F94CD33",
          fillColor: "#ffff0033",
          strokeColor: "#FFF",
          strokeWidth: 2,
          zIndex: 5,
    },{  
      points: points3,
       fillColor: "#4F94CD33",
        fillColor: "#ffff0033",
        strokeColor: "#FFF",
        strokeWidth: 2,
        zIndex: 5,
  },{  
    points: points4,
     fillColor: "#4F94CD33",
      fillColor: "#ffff0033",
      strokeColor: "#FFF",
      strokeWidth: 2,
      zIndex: 5,
},{  
  points: points5,
   fillColor: "#4F94CD33",
    fillColor: "#ffff0033",
    strokeColor: "#FFF",
    strokeWidth: 2,
    zIndex: 5,
},{  
  points: points6,
   fillColor: "#4F94CD33",
    fillColor: "#ffff0033",
    strokeColor: "#FFF",
    strokeWidth: 2,
    zIndex: 5,
}],
    mapList: [{
        text: '统战阵地',
        value: 0
      },
      {
        text: '统战组织',
        value: 1
      },
      {
        text: '商会社团',
        value: 2
      },
    ],
    scale: 10,
    currentScale:10,
    value1: 0,
    latitude: 27.9421,
    longitude: 112.869751,
    // markers: [{
    //   id: 1,
    //   latitude: 28.232109, // 纬度
    //   longitude: 112.93152, // 经度
    //   title: '地点1', // 标记点标题
    //   iconPath: '/image/images/position.png', // 标记点图标路径（可选）
    //   width:30,
    //   height:30,
    //   callout: { // 标记点气泡窗口内容（可选）
    //     content: '这里是地点1',
    //     display: 'ALWAYS' // 显示模式，可选值有'ALWAYS'、'NEVER'、'SHOW_ALL'、'SHOW_ACTIVE'等。
    //   }
    // },{
    //   id: 2,
    //   latitude: 28.232409, // 纬度
    //   longitude: 112.930152, // 经度
    //   title: '地点1', // 标记点标题
    //   iconPath: '/image/images/position.png', // 标记点图标路径（可选）
    //   width:30,
    //   height:30,
    //   callout: { // 标记点气泡窗口内容（可选）
    //     content: '这里是地点1',
    //     display: 'ALWAYS' // 显示模式，可选值有'ALWAYS'、'NEVER'、'SHOW_ALL'、'SHOW_ACTIVE'等。
    //   }
    // }],
    addressList: [],
    markerId: null,
    addressDetail: {},
    show: false,
    tabList: [{
      name: '场所',
      type: "place"
    }, {
      name: '基地',
      type: "institutions",
    }, {
      name: '民族门店',
      type: "shop",
    }],
    paramsMap: {
      name: '',
    },
    name: '',
    tabParams: {},
    active: 0,
    PolicyCurrent: 0,
    type: '',
    holidayList: [],
    showInfo: false,
    // formData: {},
    tenantId:'',
    institutionsType: [],
    dateShow: false,
    height:30,
    heightFlag:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(option) {
    // 实例化API核心类
    qqmapsdk = new QQMapWX({
      key: 'ILSBZ-GKZWW-M5TR3-YDDGT-NDACT-32FA6'
    });
    // console.log(111)
    // await this.getMapTab()
    // this.setData({
    //   'paramsMap.cateId': this.data.tabParams.id
    // })
    // this.getGroup()

  },
  changeHeight(){
    if(!this.data.heightFlag){
      this.setData({
        height:70,
        heightFlag:true
      })
    }else{
      this.setData({
        height:30,
        heightFlag:false
      })
    }
  },
  changeMapType() {},
  onClose() {
    this.setData({
      show: false,
      showInfo:false
    })
  },
  async getMapTab() {
    await api.get('/group/getTab').then(res => {
      this.setData({
        tabList: res
      })
      res.map((val, index) => {
        if (index == 0) {
          this.setData({
            tabParams: val
          })
        }
      })
    })
  },
  handleSearch() {
    if (this.data.tabParams.type === 'place') {
      this.setData({
        paramsMap: {
          name: this.data.name
        }
      })
      this.getAddress()
    } else if (this.data.tabParams.type === 'institutions') {
      this.setData({
        "paramsMap.name": this.data.name
      })
      this.getInstitutions()
    } else if (this.data.tabParams.type === 'shop') {
      this.setData({
        paramsMap: {
          name: this.data.name
        }
      })
      this.getShop()
    }
  },
  async handleMapType(e) {
    this.setData({
      tabParams: e.currentTarget.dataset.param,
      active: e.currentTarget.dataset.index,
      name: '',
      show: false
    })
    if (e.currentTarget.dataset.param.type === 'group') {
      this.setData({
        // 'paramsMap.cateId': e.currentTarget.dataset.param.id,
        'paramsMap.name': this.data.name,
      })
      // this.getGroup()
    } else if (e.currentTarget.dataset.param.type === 'place') {
      this.setData({
        type: 'place'
      })
      this.setData({
        paramsMap: {
          name: this.data.name
        }
      })
      this.getAddress()
    } else if (e.currentTarget.dataset.param.type === 'institutions') {
      await this.getinstitutionsTypeList()
      this.setData({
        type: 'institutions'
      })
      // this.setData({
      //   // 'paramsMap.name':this.data.name,
      //   name:'新阶联',
      //   paramsMap: {
      //     name: '新阶联'
      //   }

      // })
      this.getInstitutions()
    } else if (e.currentTarget.dataset.param.type === 'shop') {
      this.setData({
        type: 'shop'
      })
      this.getShop()
    }
  },
  async getinstitutionsTypeList() {
    await api.get('/dict/getByType?type=' + 'institutions_type').then(res => {
      this.setData({
        institutionsType: res,
        'paramsMap.category': res[0].value
      })
    })
  },
  handleMapTypeByName({
    currentTarget
  }) {
    this.setData({
      'paramsMap.category': currentTarget.dataset.iname,
      show: false
    })
    this.getInstitutions()

  },
  getGroup() {
    api.get('/group/page', this.data.paramsMap).then(res => {
      res.map(val => {
        val.width = 30,
          val.height = 30,
          val.customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'ALWAYS' // 或 'BYCLICK'
          }

        return val
      })
      this.setData({
        addressList: res
      })
    })
  },
  // 基地
  getInstitutions() {
    api.get('/institutions/page', this.data.paramsMap).then(res => {
      res.map(val => {
        val.iconPath = "/image/images/jd.png",

        val.width = 30,
          val.height = 30,
          val.customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'ALWAYS' // 或 'BYCLICK'
          }
        val.joinCluster = true
        return val
      })
      this.setData({
        addressList: res,
        longitude: res[0].longitude,
        latitude: res[0].latitude,
      })
    })
  },
  // 场所  
  getAddress() {
    api.get('/place/page', this.data.paramsMap).then(res => {
      res.map(val => {
        // 自定义图标
        val.iconPath = "/image/images/cs.png",
        val.width = 30,
          val.height = 30,
          val.customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'ALWAYS' // 或 'BYCLICK'
          }
        val.joinCluster = true
        return val
      })
      this.setData({
        addressList: res,
        longitude: res[0].longitude,
        latitude: res[0].latitude,
      })
      console.log(this.data.addressList,'sdfsddddddddd')

    })
  },
  getShop() {
    api.get('/shop/page', this.data.paramsMap).then(res => {
      res.map(val => {
        val.iconPath = "/image/images/md.png",
        val.width = 30,
          val.height = 30,
          val.customCallout = {
            anchorY: 0,
            anchorX: 0,
            display: 'ALWAYS' // 或 'BYCLICK'
          }
        val.joinCluster = true
        return val
      })
      this.setData({
        addressList: res,
        longitude: res[0].longitude,
        latitude: res[0].latitude,
      })
    })
  },
  // 总代码
  scaleChange(e) {
    var that = this //后面用到的this是在闭包里的，而不是指当前页面，故要先保存为that，方便下面使用
    console.log(e)
    var that = this
    if (e.type == 'end') {
      //如果用户执行的是缩放操作
      if (e.detail.scale != this.data.scale) {
        let newwidth = parseInt(3.33 * this.data.scale - 36.6)
        let newheight = newwidth //建立映射关系，得到新的宽度和高度
        //遍历markers数组，批量修改数组里的宽度和高度
        this.data.addressList.forEach(function (item, index) {
          that.setData({
            [`${item}.width`]: newwidth,
            [`${item}.height`]: newheight,
          })
        })
      }
      const currentScale = e.detail.scale;
      this.setData({
        currentScale: currentScale
      });
      console.log('当前缩放级别:', currentScale);
      // 根据缩放级别判断是否显示文字标记
      this.updateMarkers(currentScale);
    }
  },
   // 更新地图标记
   updateMarkers(scale) {
    const updatedMarkers = this.data.addressList.map(marker => {
      // 判断缩放级别是否大于15，决定是否显示文字标记
      if (scale > 15.4) {
        marker.label = {
          content: marker.name,  // 显示建筑物名称
          color: '#000000',
          fontSize: 12,
          anchorX:-50,
        };
      } else {
        marker.label = null;  // 隐藏文字标记
      }
      return marker;
    });
 
    // 更新标记数据
    this.setData({
      addressList: updatedMarkers
    });
 
    // 更新地图标记
    // const map = this.data.map;
    // map.addMarkers({
    //   markers: updatedMarkers,
    //   success: function () {
    //     console.log("Markers updated successfully.");
    //   },
    //   fail: function () {
    //     console.log("Failed to update markers.");
    //   }
    // });
  },
  // bindcallouttap({
  //   detail
  // }) {
  //   if (this.data.type !== 'shop') {
  //     this.setData({
  //       show: true
  //     })
  //   }
  // },
  bindmarkertap(e) {
    this.setData({
      markerId: e.detail.markerId,
    })
    if (this.data.type !== 'shop') {
      this.setData({
        show: true
      })
    }
    let data = {}
    if (this.data.type == 'institutions') {
      api.get('/institutions/get', {
        id: this.data.markerId
      }).then(res => {
        data = res
        data.briefDescribe = res.briefDescribe ? res.briefDescribe.replace(/\" style="/gi, '" style="width:100%;height:auto;display:block;margin: 0 auto;') : '暂无简介'
        this.setData({
          addressDetail: data
        })
      })
    } else if (this.data.type == 'shop') {
      this.data.addressList.forEach(val => {
        if (val.id == this.data.markerId) {
          console.log(val)
          this.setData({
            addressDetail: val
          })
        }
      })
      // api.get('/institutions/get', {
      //   id: this.data.markerId
      // }).then(res => {
      //   data = res
      //   data.description = res?.description.replace(/\" style="/gi, '" style="width:100%;height:auto;display:block;margin: 0 auto;"')
      //   this.setData({
      //     addressDetail: res
      //   })
      //   console.log(this.data.addressDetail,'this.data.addressDetail')
      // })
    } else {
      api.get('/place/get', {
        id: this.data.markerId
      }).then(res => {
        data = res
        data.description = res?.description.replace(/\" style="/gi, '" style="width:100%;height:auto;display:block;margin: 0 auto;')
        console.log(data.description)
        this.setData({
          addressDetail: res
        })
      })
    }
    this.getHolidayListByTenantById(e.detail.markerId)
  },
  getDetail({currentTarget}) {
    this.setData({
      markerId: currentTarget.dataset.id,
    })
    if (this.data.type !== 'shop') {
      this.setData({
        show: true
      })
    }
    let data = {}
    if (this.data.type == 'institutions') {
      api.get('/institutions/get', {
        id: this.data.markerId
      }).then(res => {
        data = res
        data.briefDescribe = res.briefDescribe ? res.briefDescribe.replace(/\" style="/gi, '" style="width:100%;height:auto;display:block;margin: 0 auto;') : '暂无简介'
        this.setData({
          addressDetail: data
        })
      })
    } else if (this.data.type == 'shop') {
      this.data.addressList.forEach(val => {
        if (val.id == this.data.markerId) {
          console.log(val)
          this.setData({
            addressDetail: val
          })
        }
      })
    } else {
      api.get('/place/get', {
        id: this.data.markerId
      }).then(res => {
        data = res
        data.description = res?.description.replace(/\" style="/gi, '" style="width:100%;height:auto;display:block;margin: 0 auto;')
        console.log(data.description)
        this.setData({
          addressDetail: res
        })
      })
    }
    this.getHolidayListByTenantById(currentTarget.dataset.id)
  },
  closeShowInfo() {
    this.setData({
      showInfo: false
    })
  },
  getHolidayListByTenantById(id) {
    this.setData({
      tenantId:id,
      // 'formData.tenantId': id,
    })
    api.get('/appointment/getHolidayListByTenantId', {
      id: id
    }).then(res => {
      this.setData({
        holidayList: res
      })
    })
  },
  confirmForm({
    currentTarget
  }) {
    // this.setData({
    //   showInfo: true,
    //   'formData.holidayId': currentTarget.dataset.id,
    // })
    wx.navigateTo({
      url: '/subPackages/pages/reservation/reservation?holidayId='+currentTarget.dataset.id+'&tenantId='+this.data.tenantId,
    })
  },
  // handleInput(e) {
  //   this.setData({
  //     'formData.contactName': e.detail
  //   })
  // },
  // blurContactMobile(e) {
  //   this.setData({
  //     'formData.contactMobile': e.detail.value
  //   })
  // },
  // bindTime() {
  //   this.setData({
  //     dateShow: true
  //   })
  // },
  // closeTime() {
  //   console.log('-----')
  //   this.setData({
  //     dateShow: false
  //   })
  // },
  confirm(e) {
    console.log(e.detail)
    // this.setData({time:e.detail})
    this.time(e.detail)
    // this.setData({dateShow: false})
  },
  time(time) {
    let y = time.getFullYear()
    // 月
    let m = time.getMonth() + 1
    m = m < 10 ? ('0' + m) : m
    // 日
    let d = time.getDate()
    d = d < 10 ? ('0' + d) : d
    // 时
    let h = time.getHours()
    h = h < 10 ? ('0' + h) : h
    // 分
    let M = time.getMinutes()
    M = M < 10 ? ('0' + M) : M
    // 秒
    let s = time.getSeconds()
    s = s < 10 ? ('0' + s) : s
    this.setData({
      'formData.appointmentTime': y + '-' + m + '-' + d + ' ' + h + ':' + M + ':' + s,
      dateShow: false
    })
  },
  blurRemark(e) {
    this.setData({
      'formData.remark': e.detail.value
    })
  },
  // handleConfirm() {
  //   api.post('/appointment/submit', this.data.formData).then(res => {
  //     wx.showToast({
  //       title: '预约成功',
  //     })
  //     this.setData({
  //       showInfo: false
  //     })
  //   })
  // },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getAddress()
    if (typeof this.getTabBar == 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        // 这里的数字对应tabbar对应的索引
        selected: 1,
      });
    }
  },
  copy({
    currentTarget
  }) {
    console.log(currentTarget.dataset.copy)
    wx.setClipboardData({
      data: currentTarget.dataset.copy,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      },
      fail: function (res) {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})